package com.stox.ui.javafx.charting.widget;

import java.util.ArrayList;
import java.util.List;

import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.TreeItem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import com.stox.event.AbstractModelSelectionEvent;
import com.stox.model.AbstractModel;
import com.stox.ui.javafx.core.util.MessageSource;
import com.stox.ui.javafx.core.widget.wrapper.MenuItem;
import com.stox.ui.javafx.navigator.model.AbstractModelTreeItem;
import com.stox.ui.javafx.navigator.view.tab.scrip.ScripNavigatorTab;
import com.stox.ui.javafx.navigator.view.tab.scrip.ScripNavigatorTabContextMenu;
import com.stox.util.ApplicationContextUtil;

@Component
public class ShowChartsMenuItem extends MenuItem implements EventHandler<ActionEvent> {

	@Autowired
	private ApplicationEventPublisher applicationEventPublisher;
	
	public ShowChartsMenuItem() {
		super(MessageSource.getMessage("Show.Chart"),"Ctrl+N","");
		setOnAction(this);
	}
	
	@Override
	public void handle(ActionEvent event) {
		ScripNavigatorTab tab = ApplicationContextUtil.getApplicationContext().getBean(ScripNavigatorTab.class);
		ObservableList<TreeItem<String>> items = tab.getTreeView().getSelectionModel().getSelectedItems();
		if(null != items && !items.isEmpty()) {
			List<AbstractModel> models = new ArrayList<AbstractModel>();
			for(TreeItem<String> item : items) {
				if(item instanceof AbstractModelTreeItem) {
					AbstractModelTreeItem<?> abstractModelTreeItem = (AbstractModelTreeItem<?>)item;
					models.add(abstractModelTreeItem.getModel());
				}
			}
			applicationEventPublisher.publishEvent(new AbstractModelSelectionEvent<AbstractModel>(models));
		}
	}
	
	@Override
	public int getOrder() {
		return 0;
	}

	@Override
	public Class<?> getParentClass() {
		return ScripNavigatorTabContextMenu.class;
	}

}
